package com.xuwang.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuwang.Common.Constast;
import com.xuwang.Util.ExcelImage;
import com.xuwang.Util.JWTutil;
import com.xuwang.Util.TableResult;
import com.xuwang.Util.sendValidCode;
import com.xuwang.mapper.PublicInfoMapper;
import com.xuwang.pojo.Comment;
import com.xuwang.pojo.User;
import com.xuwang.service.PublicInfoService;
import javafx.scene.control.Tab;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author smallseven
 * @version 1.0
 * @since 2021-08-31 15:29:52
 */
@Service
public class PublicInfoServiceImpl implements PublicInfoService {
    @Resource
    private PublicInfoMapper publicationMapper;

    /**
     * 添加用户 从前端获取的数据（0,1）转换为可用数据
     *
     * @param user
     * @return
     */
    @Override
    public TableResult<String> register(User user) {
        TableResult<String> result;
        user.setUserLevel(0);
        int isSuccess = publicationMapper.register(user);

        //插入默认的评论
        Comment comment=new Comment();
        Timestamp time = new Timestamp(System.currentTimeMillis());
        comment.setTime(time);
        comment.setUserId(user.getId());
        comment.setScore(3.0);
        comment.setCommentTaste(3.0);
        comment.setCommentServe(3.0);
        comment.setCommentEnvironment(3.0);
        comment.setCommentContent("一般好吃");
        comment.setObjId(1);
        int isSuccess01=publicationMapper.addComment(comment);
        if (isSuccess == 1) {
            result = new TableResult<>(200, Constast.REGISTER_SUCCESS, 1, "");
        } else {
            result = new TableResult<>(500, Constast.REGISTER_ERROR, 0, "");
        }
        return result;
    }

    /**
     * 如果用户登录成功，封装token进heard头里面
     *
     * @param user
     * @return
     */
    @Override
    public TableResult<HttpServletResponse> login(User user, HttpServletResponse response) throws Exception {
        TableResult<HttpServletResponse> result;
        User resultUser = publicationMapper.login(user);
        //登录成功 封装token
        Map<String, String> map;
        if (resultUser.getId() != -1) {
            map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("identity", resultUser.getIdentity() + "");
            String token = JWTutil.createToken(map);
            response.setHeader("Access-control-Expose-Headers", "authorization");
            response.setHeader("authorization", token);
            //将token封装到数据库中
            publicationMapper.saveToken(user.getUsername(), token);

            //返回JSON
            result = new TableResult<>(200, Constast.LOGIN_SUCCESS, resultUser.getIdentity(), response);
        } else {
            result = new TableResult<>(500, Constast.PASSWORD_ERROR, -1, response);
        }

        return result;
    }

    /**
     * 查询当前操作是注册还是登录，如果数据库中存在该手机号就是登录，注册则无。
     *
     * @param phoneNum
     * @param code
     * @return
     */
    @Override
    public TableResult<Integer> updateCode(String phoneNum, int code) {
        TableResult<Integer> result;
        //返回条数为0则为注册
        int thisPhone = publicationMapper.findThisPhone(phoneNum);
        if (thisPhone == 0) {
            result = new TableResult<>(200, Constast.PHONE_CODE_SUCCESS, 1, 1);
        } else
            result = new TableResult<>(200, Constast.PHONE_CODE_SUCCESS, 1, publicationMapper.updateCode(phoneNum, code));
        return result;
    }

    /**
     * 修改用户的头像
     *
     * @param src
     * @param token
     * @return
     */
    @Override
    public TableResult<String> updateUserImg(String src, String token) {
        String username = JWTutil.getUserName(token);
        int isSuccess = publicationMapper.updateUserImg(username, src);
        TableResult<String> result;
        if (isSuccess == 1) {
            result = new TableResult<>(200, "修改成功", 1, "");
        } else {
            result = new TableResult<>(500, "修改失败", 0, "");
        }
        return result;
    }

    /**
     * 修改用户基本信息
     *
     * @param user
     * @return
     */
    @Override
    public TableResult<String> updateUserInfo(User user) {
        int isSuccess = publicationMapper.updateUserInfo(user);
        TableResult<String> result;
        if (isSuccess == 1) {
            result = new TableResult<>(200, "修改用户信息成功", 1, "");
        } else {
            result = new TableResult<>(500, "修改用户信息失败", 0, "");
        }
        return result;
    }

    /**
     * 批量插入用户数据和头像
     *
     * @param path
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Override
    public TableResult<String> insertManyUser(String path, HttpServletRequest request) throws IOException, InvalidFormatException {
        List<User> userList = ExcelImage.getUserInfos(path,request);
        int isSuccess = publicationMapper.insertManyUser(userList);
        TableResult<String> result;
        if (isSuccess >= 1) {
            result = new TableResult<>(200, Constast.INSERT_COMPLETE, userList.size(), "");
        } else {
            result = new TableResult<>(500, Constast.INSERT_ERROR, 0, "");
        }
        return result;
    }

    @Override
    public User checkUserName(String userName) {
        User user ;
        user = publicationMapper.checkUserName(userName);
        return user;
    }

    @Override
    public TableResult<String> deleteManyUser(Integer[] ids) {
        TableResult<String> result ;
        System.out.println(Arrays.toString(ids));
        int isSucceed=publicationMapper.deleteManyUser(ids);
        if (isSucceed >= 1) {
            result=new TableResult<>(200, Constast.DELETE_SUCCESS, isSucceed,"");
        }else {
            result=new TableResult<>(500, Constast.ADMIN_NULL, 0,"");
        }
        return result;
    }
}
